package model;

import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

//public class CoOccurrenceMatrixBuilder {
//    private Map<String, Map<String, Integer>> coOccurrenceMatrix = new HashMap<>();
//
//    public void buildMatrix(List<String> searchTerms) {
//        for (int i = 0; i < searchTerms.size(); i++) {
//            String termA = searchTerms.get(i);
//            coOccurrenceMatrix.putIfAbsent(termA, new HashMap<>());
//
//            for (int j = 0; j < searchTerms.size(); j++) {
//                if (i != j) {
//                    String termB = searchTerms.get(j);
//                    Map<String, Integer> map = coOccurrenceMatrix.get(termA);
//                    map.put(termB, map.getOrDefault(termB, 0) + 1);
//                }
//            }
//        }
//    }
//
//    public Map<String, Integer> getCoOccurrences(String term) {
//        return coOccurrenceMatrix.getOrDefault(term, new HashMap<>());
//    }
//}
@Service
public class CoOccurrenceMatrixBuilder {
    private Map<String, Map<String, Integer>> coOccurrenceMatrix = new HashMap<>();

    public void buildMatrix(List<String> searchTerms) {
        for (int i = 0; i < searchTerms.size(); i++) {
            String termA = searchTerms.get(i);
            coOccurrenceMatrix.putIfAbsent(termA, new HashMap<>()); // 确保每个词项都有一个映射的HashMap

            for (int j = 0; j < searchTerms.size(); j++) {
                if (i != j) {
                    String termB = searchTerms.get(j);
                    Map<String, Integer> map = coOccurrenceMatrix.get(termA); // 获取当前词项的映射HashMap
                    map.put(termB, map.getOrDefault(termB, 0) + 1); // 增加或更新词项B与词项A的共现次数
                }
            }
        }
    }

    public List<String> getRecommendations(String searchTerm, int limit) {
        if (!coOccurrenceMatrix.containsKey(searchTerm)) return new ArrayList<>(); // 如果搜索词不在矩阵中，返回空列表
        return coOccurrenceMatrix.get(searchTerm).entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) // 按共现次数降序排序
                .map(Map.Entry::getKey) // 提取词项
                .limit(limit) // 限制返回的推荐数量
                .collect(Collectors.toList()); // 收集结果为列表
    }

    public void printMatrix() {
        System.out.println("共现矩阵内容:");
        coOccurrenceMatrix.forEach((termA, map) -> {
            map.forEach((termB, count) -> {
                System.out.println(termA + " 和 " + termB + " 共现次数: " + count);
            });
        });
    }

    // 新添加的方法，用于获取与指定搜索词共现的所有词汇及其次数
    public Map<String, Integer> getCoOccurrences(String searchTerm) {
        // 返回与给定词汇共现的词汇及其次数，如果不存在，则返回一个空的HashMap
        return coOccurrenceMatrix.getOrDefault(searchTerm, new HashMap<>());
    }
}

